package test.hystrix.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.netflix.hystrix.HystrixCollapser.CollapsedRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

public class CollapserCommand extends HystrixCommand<Map<String,String>>{
	private Collection<CollapsedRequest<String,String>> requests;
	private CloseableHttpClient httpClient;
	protected CollapserCommand(Collection<CollapsedRequest<String,String>> requests) {
		super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
		this.requests = requests;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Map<String, String> run() throws Exception {
		httpClient = HttpClients.createDefault();
		System.out.println("收集参数后执行命令,参数数量"+requests.size());
		//处理参数
		List<String> params = new ArrayList<>();
		for(CollapsedRequest<String,String> rquest:requests) {
			params.add(rquest.getArgument());
		}
		try {
			StringBuilder url = new StringBuilder("http://localhost:8080/normalVisits");
			if(!params.isEmpty()) {
				url.append("?").append("buildNames=");
				params.forEach(ele->{
					url.append(ele).append(",");
			   });
			}
			url.deleteCharAt(url.lastIndexOf(","));
			System.out.println(url.toString());
			HttpGet httpget =new HttpGet(url.toString());
			HttpResponse response = httpClient.execute(httpget) ;
			return JSONObject.toJavaObject(JSON.parseObject(EntityUtils.toString(response.getEntity())), Map.class);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
